import { stringify } from 'querystring';
import { history, Reducer, Effect } from 'umi';

import { fakeAccountLogin, LoginData, logout, queryCurrentUserInfo } from '@/services/login';
import { getAuthority, getAuthorityAdmin, getUserData, setAuthority, setUserData } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { message } from 'antd';

export interface returnState {}

export interface StateType {
  status?: 'ok' | 'error';
  type?: string;
  currentAuthority?: 'user' | 'guest' | 'admin';
  userData?: LoginData;
}

export interface LoginModelType {
  namespace: string;
  state: StateType;
  effects: {
    login: Effect;
    logout: Effect;
    getUserInfo: Effect;
  };
  reducers: {
    changeLoginStatus: Reducer<StateType>;
    setUserInfoData: Reducer<StateType>;
  };
}

const Model: LoginModelType = {
  namespace: 'login',

  state: {
    status: undefined,
    userData: {},
  },

  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(fakeAccountLogin, payload);
      // Login successfully
      if (response?.responseCode == 200) {
        yield put({
          type: 'changeLoginStatus',
          payload: response?.data ?? {},
        });

        //本地存入用户ID
        setUserData(response?.data?.id);
        setAuthority(getAuthorityAdmin(response?.data.userGroup));

        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        message.success('登录成功！');
        //判断登录时是否有重定向
        let { redirect } = (params as { redirect: string }) ?? {};
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = '/';
            return;
          }
        }
        history.replace(redirect || '/');
      } else {
        message.error(response?.responseMessage);
      }
    },

    *logout({ payload }, { call, put }) {
      const response = yield call(logout, payload);

      if (response?.responseCode == 200) {
        const { redirect } = getPageQuery();
        // Note: There may be security issues, please note

        // 判断只有admin 用户才有重定向
        let str: any = getAuthority();
        if (window.location.pathname !== '/user/login' && !redirect) {
          history.replace({
            pathname: '/user/login',
            search:
              str == 'admin'
                ? stringify({
                    redirect: window.location.href,
                  })
                : '',
          });
        }
      }
    },

    *getUserInfo({ payload }, { call, put }) {
      const id = getUserData();
      const response = yield call(queryCurrentUserInfo, { id });
      yield put({
        type: 'setUserInfoData',
        payload: response?.data ?? {},
      });
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      return {
        ...state,
      };
    },
    setUserInfoData(state, { payload }) {
      return {
        ...state,
        userData: payload,
      };
    },
  },
};

export default Model;
